﻿using SPSDeploy.Extensions.Configuration;
using System;
using System.Globalization;
using System.Linq;
using System.Security;
using System.Text;
using System.Xml.Linq;

namespace SPSDeploy.Extensions
{
    /// <summary>
    /// Utility methods
    /// </summary>
    internal static class Tools
    {

        // Constants
        internal const string DATE_FORMAT = "yyyy-MM-dd";

        /// <summary>
        /// Rollup parent / child elements
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="child"></param>
        internal static void RollupElement(XElement parent, XElement child)
        {
            if (child.HasElements)
                parent.Add(child);
        }

        /// <summary>
        /// Return account password
        /// </summary>
        /// <param name="accountName"></param>
        /// <returns></returns>
        internal static SecureString GetAccountPassword(string accountName)
        {
            if (ApplicationSection.Instance.Accounts.Contains(accountName))
            {
                SecureString result = new SecureString();
                ApplicationSection.Instance.Accounts[accountName].Password.ToCharArray().ToList().ForEach(result.AppendChar);
                return result;
            }
            throw new Exception(string.Format("Account '{0}' password not configured.", accountName));
        }

        /// <summary>
        /// Return formatted bypass List text
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        internal static string GetBypassListText(string[] list)
        {
            if (list == null || list.Length == 0)
                return string.Empty;
            StringBuilder result = new StringBuilder();
            list.ToList().ForEach(i => result.Append(i.Replace(";", "").Trim()).Append(';'));
            return result.ToString();
        }

        /// <summary>
        /// Return date time text value
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        internal static string GetDateValue(DateTime? value)
        {
            return value != null ? value.Value.ToString(DATE_FORMAT) : string.Empty;
        }

        /// <summary>
        /// Return UTC date time value from text
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        internal static DateTime? GetDateValueUTC(string value)
        {
            if (!string.IsNullOrEmpty(value))
                return DateTime.ParseExact(value, DATE_FORMAT, CultureInfo.InvariantCulture).ToUniversalTime();
            return null;
        }

    }
}